package com.david.viewtest.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ImageSpan
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

/**
 * 云端icon 文本长时换行的带标签labelView，如果最多一行时可使用TextLabelView放在此View后面
 *
 * TODO 下载云端icon并展示，glide下载图片下载完成时展示
 */
class TextCloudIconsLabelView(context: Context, attrs: AttributeSet): AppCompatTextView(context, attrs) {
    fun setContentAndTag(content: String?, startTagReses: List<Int>? = null, endTagReses: List<Int>?) {
        if (startTagReses.isNullOrEmpty() && endTagReses.isNullOrEmpty()) {
            text = content
            return
        }


        val builder = SpannableStringBuilder()
        if (!startTagReses.isNullOrEmpty()) {
            for (res in startTagReses) {
                builder.append(" ")

                val bitmap: Bitmap = BitmapFactory.decodeResource(context.resources, res)
                val d: Drawable = BitmapDrawable(context.resources, bitmap)
                d.setBounds(0, 0, bitmap.width, bitmap.height);//缺少这句的话，不会报错，但是图片不回显示
                builder.setSpan(ImageSpan(d, ImageSpan.ALIGN_CENTER), builder.length - 1, builder.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

                builder.append(" ")
            }
        }
        builder.append(content)


        if (!endTagReses.isNullOrEmpty()) {
            for (res in endTagReses) {
                builder.append("  ")

                val bitmap: Bitmap = BitmapFactory.decodeResource(context.resources, res)
                val d: Drawable = BitmapDrawable(context.resources, bitmap)
                d.setBounds(0, 0, bitmap.width, bitmap.height);//缺少这句的话，不会报错，但是图片不回显示

                builder.setSpan(ImageSpan(d, ImageSpan.ALIGN_CENTER), builder.length - 1, builder.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
        }
        text = builder
    }
}